#!/bin/bash

# Docling Web App - 虚拟环境安装脚本
# 使用Python venv模块创建虚拟环境并安装依赖

set -e  # 遇到错误时退出

echo "🚀 开始设置 Docling Web 应用虚拟环境..."
echo "=================================================="

# 检查Python版本
echo "📋 检查Python环境..."
python3 --version || {
    echo "❌ 错误: 未找到 python3，请先安装 Python 3.8+"
    exit 1
}

# 获取当前目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
VENV_DIR="$SCRIPT_DIR/venv"

echo "📁 项目目录: $SCRIPT_DIR"
echo "📁 虚拟环境目录: $VENV_DIR"

# 删除已存在的虚拟环境
if [ -d "$VENV_DIR" ]; then
    echo "🗑️  删除已存在的虚拟环境..."
    rm -rf "$VENV_DIR"
fi

# 创建虚拟环境
echo "🔧 创建Python虚拟环境..."
python3 -m venv "$VENV_DIR"

# 激活虚拟环境
echo "⚡ 激活虚拟环境..."
source "$VENV_DIR/bin/activate"

# 升级pip
echo "📦 升级pip..."
pip install --upgrade pip

# 安装基础依赖
echo "📦 安装基础依赖..."
pip install wheel setuptools

# 检查requirements.txt文件
if [ ! -f "$SCRIPT_DIR/requirements.txt" ]; then
    echo "❌ 错误: 未找到 requirements.txt 文件"
    exit 1
fi

# 安装项目依赖
echo "📦 安装项目依赖..."
echo "这可能需要几分钟时间，请耐心等待..."

# 首先安装numpy（避免版本冲突）
echo "📦 安装numpy..."
pip install "numpy<2"

# 安装Flask
echo "📦 安装Flask..."
pip install Flask==3.0.0

# 安装Docling（不包含VLM）
echo "📦 安装Docling..."
pip install docling

# 安装其他依赖
echo "📦 安装其他依赖..."
pip install -r requirements.txt || {
    echo "⚠️  警告: 部分依赖安装失败，尝试单独安装核心依赖..."
    
    # 核心依赖列表
    CORE_DEPS=(
        "Flask==3.0.0"
        "Werkzeug==3.0.1"
        "docling"
        "huggingface_hub"
        "transformers"
        "torch"
        "pandas"
        "pillow"
        "requests"
        "pydantic"
        "python-dotenv"
    )
    
    for dep in "${CORE_DEPS[@]}"; do
        echo "📦 安装 $dep..."
        pip install "$dep" || echo "⚠️  跳过 $dep"
    done
}

# 创建必要的目录
echo "📁 创建必要目录..."
mkdir -p "$SCRIPT_DIR/uploads"
mkdir -p "$SCRIPT_DIR/models_cache"
mkdir -p "$SCRIPT_DIR/static/uploads"

# 设置环境变量
echo "🔧 配置环境变量..."
export HF_ENDPOINT=https://hf-mirror.com
export HF_HOME="$SCRIPT_DIR/models_cache"
export OMP_NUM_THREADS=4

# 创建环境变量文件
cat > "$SCRIPT_DIR/.env" << EOF
# Docling Web App 环境变量配置
HF_ENDPOINT=https://hf-mirror.com
HF_HOME=$SCRIPT_DIR/models_cache
OMP_NUM_THREADS=4
USE_VLM_PROCESSOR=false
DEFAULT_PROCESSOR=standard
FLASK_DEBUG=true
EOF

echo "✅ 虚拟环境设置完成！"
echo "=================================================="
echo ""
echo "🎯 下一步操作："
echo "1. 激活虚拟环境:"
echo "   source venv/bin/activate"
echo ""
echo "2. 启动应用:"
echo "   python app.py"
echo ""
echo "3. 访问应用:"
echo "   http://localhost:5000"
echo ""
echo "4. 停用虚拟环境:"
echo "   deactivate"
echo ""
echo "📋 虚拟环境信息:"
echo "   位置: $VENV_DIR"
echo "   Python: $(python3 --version)"
echo "   Pip: $(pip --version)"
echo ""
echo "🔧 如需启用VLM处理器，请编辑 .env 文件:"
echo "   USE_VLM_PROCESSOR=true"
echo "   DEFAULT_PROCESSOR=vlm"
